/*
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-03-20 14:42:28
 * @Description  : 用于发送验证码的hooks
 */
import { useMessage } from 'naive-ui'
import { sendEmailCode } from '@/api/user'
import type { SendEmailReq } from '@/types/user'
import { CODE_TIME } from '@/constants'
import { load } from '@/utils/loading'

export const useSendCode = () => {
  const message = useMessage()
  const timer = ref()
  const emailCodeSecond = ref(0)
  const sendCode = (
    businessType: string,
    methodType: string,
    email: string,
    picCode?: string
  ) => {
    // 发送邮箱验证码接口
    if (emailCodeSecond.value !== 0) {
      return
    }

    load.show()
    const reqBody: SendEmailReq = {
      businessType,
      methodType,
      email
    }
    picCode !== undefined && (reqBody.picCode = picCode)
    sendEmailCode(reqBody)
      .then(() => {
        message.success('验证码已发送')
        emailCodeSecond.value = CODE_TIME
        timer.value = setInterval(() => {
          emailCodeSecond.value -= 1
          if (emailCodeSecond.value <= 0) {
            emailCodeSecond.value = 0
            clearInterval(timer.value)
          }
        }, 1000)
      })
      .catch(console.error)
      .finally(() => {
        load.hide()
      })
  }

  onBeforeUnmount(() => {
    // 清除定时器
    clearInterval(timer.value)
    timer.value = null
  })

  return {
    sendCode,
    emailCodeSecond
  }
}
